import cfg from './config.js'


// 跳转目标
function loginRefresh(fromType,onError) {
	let target = cfg.target[fromType]
	if (!target) {
		return;
	}
	console.log('start login target is :' + target)

	wx.qy.login({
		success: (res) => {
			if (res.errMsg == 'qy__login:ok') {
				let code = res.code

				uni.request({
					url: cfg.host + 'wx/cp/common/getOpenIdByCode?code=' + code,
					method: 'GET',
					success: (res1) => {
						if (res1.data) {
							if (res1.data.code == 0) {
								let userId = res1.data.data.userId;
								let openId = res1.data.data.openId;
								cfg.saveOpenUserId(userId, openId)

								uni.redirectTo({
									url: target,
									fail: () => {
										console.log('login redirect fail')
									}
								})
							} else {
								onError()
							}
						}
					},
					fail: () => {
						onError()
					},
				})
			}
		},
		fail: () => {
			console.log('jscode fail')
			onError()
		},

	})
}

export default {
	loginRefresh
}